package com.neusoft.hifly.push.config;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.neusoft.hifly.core.token.JwtUtil;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.core.token.config.JwtConfig;
import com.neusoft.hifly.core.token.domain.TokenVO;
import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * Feign拦截器
 */
public class FeignClientIntercepter implements RequestInterceptor {

	private final JwtConfig jwtConfig;

	public FeignClientIntercepter(final JwtConfig jwtConfig) {
		this.jwtConfig = jwtConfig;
	}

	@Override
	public void apply(final RequestTemplate requestTemplate) {
		// TODO Feign之间传递token解决方案
		try {
			final Map<String, String> headers = getHeaders();
			if (headers.isEmpty()) {
				final TokenVO tokenVO = TokenContextHolder.get();
				if (tokenVO != null) {
					// 可能是Junit提交的
					requestTemplate.header(JwtUtil.TOKEN_KEY,
							JwtUtil.createPayLoad(jwtConfig.getSecret(), jwtConfig.getExpire(), tokenVO));
				}
			}
			for (final String headerName : headers.keySet()) {
				requestTemplate.header(headerName, headers.get(headerName));
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前URL请求头信息
	 *
	 * @return 头信息
	 */
	private Map<String, String> getHeaders() {
		final Map<String, String> map = new LinkedHashMap<>(0);
		final ServletRequestAttributes servlet = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes());
		if (servlet == null) {
			return map;
		}
		final HttpServletRequest request = servlet.getRequest();
		final Enumeration<String> enumeration = request.getHeaderNames();
		while (enumeration.hasMoreElements()) {
			final String key = enumeration.nextElement();
			final String value = request.getHeader(key);
			map.put(key, value);
		}
		return map;
	}
}